package cn.hanyx.coder.core.concurrent.rw;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.StampedLock;

/**
 * StampedSample
 *
 * @author hanyx
 * @date 2020/05/29
 */
public class StampedSample {
    private final StampedLock sl = new StampedLock();
    private final Map<String, String> map = new HashMap<>();
    public String get(String key) {
        // 使用乐观读锁
        long stamp = sl.tryOptimisticRead();
        try {
            System.out.println("读锁锁定！");
            // 如果有写锁被占用，可能造成数据不一致，所以要切换到普通读锁模式
            if (!sl.validate(stamp)) {
                stamp = sl.readLock();
                return this.map.get(key);
            }
        } finally {
            sl.unlockRead(stamp);
        }
        return "";
    }

    public void put(String key, String val) {
        //涉及对共享资源的修改，使用写锁-独占操作
        long stamp = sl.writeLock();
        try {
            System.out.println("写锁锁定！");
            this.map.put(key, val);
        } finally {
            sl.unlockWrite(stamp);
        }
    }

    public static void main(String[] args) throws Exception {
        StampedSample sample = new StampedSample();
        Thread thread01 = new Thread(() -> {
            sample.put("aaa", "aaa");
        });
        Thread thread02 = new Thread(() -> {
            sample.put("bbb", "bbb");
        });
        Thread thread03 = new Thread(() -> {
            System.out.println(sample.get("aaa"));
        });
        thread01.start();
        thread02.start();
        thread03.start();
        thread01.join();
        thread02.join();
        thread03.join();
    }
}
